package com.shop.thread.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreeThreadPrint2 {

    private static int num = 0 ;

    private static int count = 0 ;

    private static ReentrantLock lock = new ReentrantLock();

    private static volatile boolean flag = true;

    public static void main(String[] args) {
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();

        new Thread(()->{
            while (flag){
                lock.lock();
                try{
                    while (num % 3 != 0){
                        conditionA.await();
                    }
                    System.out.println("A");
                    num++;
                    count ++;
                    if (count == 10){
                        flag = false;
                    }
                    conditionB.signal();
                }catch (Exception e){
                }finally {
                    lock.unlock();
                }
            }
        }).start();

        new Thread(()->{
            while (flag){
                lock.lock();
                try{
                    while (num % 3 != 1){
                        conditionB.await();
                    }
                    System.out.println("B");
                    num++;
                    conditionC.signal();
                }catch (Exception e){
                }finally {
                    lock.unlock();
                }
            }
        }).start();
        new Thread(()->{
            while (flag){
                lock.lock();
                try{
                    while (num % 3 != 2){
                        conditionC.await();
                    }
                    System.out.println("C");
                    num++;
                    conditionA.signal();
                }catch (Exception e){
                }finally {
                    lock.unlock();
                }
            }
        }).start();
    }
}
